﻿using System.Linq;
using System.Web.Mvc;
using System.Xml.Linq;
using CharacterModel;
using Framework.Model;

namespace MvcApplication1.Controllers
{
    public class FaceLoadUtilityController : Controller
    {
        private readonly Repository _repository;

        public FaceLoadUtilityController(Repository repository)
        {
            _repository = repository;
        }

        public ActionResult Upload()
        {
            return View();
        }

        public ActionResult UpdateFaceMarkersFromFeatures()
        {
            var features = _repository.FindAll<Feature>();
            var headFeatures = features
                .Where(f => f.FeatureType.FeatureTypeEnum == FeatureTypeEnum.Head)
                .ToDictionary(f => f.Name);

            var nonHeadFeatures = features
                .Where(f => f.FeatureType.FeatureTypeEnum != FeatureTypeEnum.Head);

            foreach (var feature in nonHeadFeatures.Where(f => headFeatures.ContainsKey(f.Name)))
            {
                var headFeature = headFeatures[feature.Name];
                var headMarkers = headFeature.MarkerPoints.ToDictionary(mp => mp.MarkerPointType.Id);
                var newMarkerPoints = feature.MarkerPoints.Where(mp => !headMarkers.ContainsKey(mp.MarkerPointType.Id));
                if (!newMarkerPoints.Any())
                    continue;

                foreach (var mp in newMarkerPoints)
                    headFeature.MarkerPoints.Add(new MarkerPoint
                                                     {
                                                         MarkerPointType = mp.MarkerPointType,
                                                         PointX = mp.PointX,
                                                         PointY = mp.PointY
                                                     });

                _repository.Save(headFeature);
            }


            return View("Save");
        }

        public ActionResult Save()
        {
            foreach (string file in Request.Files)
            {
                var postedFile = Request.Files[file];
                var document = XDocument.Load(postedFile.InputStream);
                var features = Feature.FromSvg(document, postedFile.FileName);
                foreach (var feature in features)
                {
                    var existingFeature = _repository
                        .Find<Feature>(f => f.Name == feature.Name && f.FeatureType.Id == feature.FeatureType.Id)
                        .FirstOrDefault();
                    if (existingFeature != null) feature.Id = existingFeature.Id;
                    _repository.Save(feature);
                }
            }
            return View();
        }
    }
}